package com.guo.redis.config.nosql;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

/**
 * RedisConfig shiyong Lettuce 做連接池
 *
 * @author H2014046
 * 2021/6/22 下午 05:05
 * @desc 增加 消息监听器容器，并适配自定义消息监听器
 */
@Configuration
public class LettuceRedisConfig {

    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }

    // 消息监听器容器定义
    @Bean
    RedisMessageListenerContainer container(LettuceConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter, ChannelTopic channelTopic){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, channelTopic);

        return container;
    }

    // 定义一个 消息监听器的适配器， 将我们自己定义的 receiver 转换成监听器
    @Bean
    MessageListenerAdapter listenerAdapter(RedisSubscribe receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    // 消息的 topic
    @Bean
    ChannelTopic channelTopic(){
        return new ChannelTopic("test");
    }

    // 我们自己定义的 receiver
    @Bean
    RedisSubscribe redisSubscribe(){
        return new RedisSubscribe();
    }

}
